# PowerShell script to add or modify system environment variables
# Run this script with administrator privileges

param (
    [Parameter(Mandatory=$true)]
    [string]$VariableName,
    
    [Parameter(Mandatory=$true)]
    [string]$VariableValue,
    
    [Parameter(Mandatory=$false)]
    [ValidateSet("User", "System")]
    [string]$Target = "User"
)

# Check if running with administrator privileges
function Test-Admin {
    $currentUser = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
    return $currentUser.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

# Administrator privileges required for system variables
if ($Target -eq "System" -and -not (Test-Admin)) {
    Write-Error "Administrator privileges required to modify system environment variables. Please restart this script as Administrator."
    exit 1
}

# For path-type variables, ensure the path exists
if ($VariableName -like "*_HOME" -or $VariableName -like "*_PATH" -or $VariableName -like "*_DIR") {
    if (-not (Test-Path $VariableValue)) {
        Write-Warning "The specified path '$VariableValue' does not exist. Continue? (Y/N)"
        $response = Read-Host
        if ($response -ne "Y" -and $response -ne "y") {
            Write-Output "Operation cancelled."
            exit 0
        }
    }
}

# Get current environment variable value
$currentValue = $null
if ($Target -eq "User") {
    $currentValue = [Environment]::GetEnvironmentVariable($VariableName, [EnvironmentVariableTarget]::User)
} else {
    $currentValue = [Environment]::GetEnvironmentVariable($VariableName, [EnvironmentVariableTarget]::Machine)
}

# Check if variable already exists
if ($currentValue -eq $VariableValue) {
    Write-Output "Environment variable '$VariableName' already exists with the same value. No update needed."
    exit 0
} elseif ($currentValue) {
    Write-Warning "Environment variable '$VariableName' already exists with value: $currentValue"
    Write-Warning "Do you want to overwrite it with the new value: $VariableValue? (Y/N)"
    $response = Read-Host
    if ($response -ne "Y" -and $response -ne "y") {
        Write-Output "Operation cancelled."
        exit 0
    }
}

# Update environment variable
try {
    if ($Target -eq "User") {
        [Environment]::SetEnvironmentVariable($VariableName, $VariableValue, [EnvironmentVariableTarget]::User)
    } else {
        [Environment]::SetEnvironmentVariable($VariableName, $VariableValue, [EnvironmentVariableTarget]::Machine)
    }
    Write-Output "Successfully set environment variable '$VariableName' to '$VariableValue' ($Target level)."
    
    # If variable is a *_HOME type commonly added to PATH, offer to add its bin directory to PATH
    if ($VariableName -like "*_HOME" -and -not ($VariableName -eq "USERPROFILE" -or $VariableName -eq "HOMEPATH")) {
        Write-Warning "Detected a *_HOME type variable. Do you want to add its bin directory to PATH? (Y/N)"
        $response = Read-Host
        if ($response -eq "Y" -or $response -eq "y") {
            $binPath = Join-Path $VariableValue "bin"
            if (Test-Path $binPath) {
                # Call the script to add PATH
                & ".\Add-PathToEnvironment.ps1" -PathToAdd $binPath -Target $Target
            } else {
                $libPath = Join-Path $VariableValue "lib"
                if (Test-Path $libPath) {
                    # Call the script to add PATH
                    & ".\Add-PathToEnvironment.ps1" -PathToAdd $libPath -Target $Target
                } else {
                    Write-Warning "Could not find standard bin or lib directory. Do you want to add the variable value itself to PATH? (Y/N)"
                    $response = Read-Host
                    if ($response -eq "Y" -or $response -eq "y") {
                        & ".\Add-PathToEnvironment.ps1" -PathToAdd $VariableValue -Target $Target
                    }
                }
            }
        }
    }
    
    Write-Output "Please restart PowerShell or open a new command window for the changes to take effect."
} catch {
    Write-Error "Unable to update environment variable: $_"
    exit 1
} 